/*
 * @Description  : SRAM控制代码
 * @authorName   : GuoJi
 * @github       : https://github.com/guoji-kk
 * @gitee        : https://gitee.com/guoji13663585559
 * @email        : 13663585559@163.com
 * @version      : 1.0
 * @Date         : 2023-06-04 19:29:12
 * @LastEditTime : 2023-06-08 09:20:09
 */

module sram_ctl(input  clk,
                input  rd_en,
                input  wr_en,
                input  [63:0] data_in,
                output reg [79:0] data_out,
                output reg key_load,
                output reg data_load 
                );
//sram存储：
//0开始是明文加密钥，一组为160位  从40开始是加密之后的结果
reg [79:0] mem[63:0];
//状态
reg [2 :0]state;
reg [6:0] cnt_out;
reg [6:0] cnt_in;

//是否开启连续模式
`define continuous 

parameter S0=3'b000,  //起始状态
          S1=3'b001,  //输出data
          S2=3'b010,  //保持输出data
          S3=3'b011,  //输出key
          S4=3'b100,  //保持输出key
          S5=3'b101,  //等待加密完成
          S6=3'b110;  //加密完成

initial begin
   state=S0;
   key_load = 0;
   data_load = 0;
   cnt_in = 0;
   cnt_out = 0;
end

always @(posedge clk ) begin
  case(state) 
    S0: begin  //开始输出数据
      if(rd_en)
      state <= S1;
      else begin
      state<=S0;
      key_load = 0;
      data_load = 0;
      end
    end
    S1: begin  //输出data
    data_out <= mem[cnt_out];
    data_load <= 1;
    state <= S2;
    end
    S2:begin //延迟一个周期
    data_out <= mem[cnt_out];
    data_load <= 1;
    state <= S3;
    cnt_out<=cnt_out+1;   
    end
    S3:begin //发送密钥
    data_out <= mem[cnt_out];
    key_load <= 1;
    data_load <= 0;
    state <= S4;   
    end
    S4:begin //延迟
    data_out <= mem[cnt_out];
    key_load <= 1;
    state <= S5;   
    cnt_out<=cnt_out+1;   
    end
    S5:begin //等待加密完成
    key_load <= 0;
     if(wr_en)begin
     mem[cnt_in+40] <= {{16{1'b0}},data_in};
     //data_out <= data_in;
     cnt_in = cnt_in + 1;
     state <= S6;   
     end
     else begin
     state <= S5;   
     end
   end
   S6: begin
`ifdef continuous
   state <= S1;
`else
   state <= S0; 
`endif 
   end
  endcase
end

endmodule


